﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

using Wicresoft.Framework.Organization;
using Wicresoft.Framework.Applications;


public partial class Page_OrganList : Wicresoft.Framework.Authentication.BasePage
{
    public bool ShowFullDepartments
    {
        get
        {
            string showFullDepartments = Request.QueryString["ShowFullDepartments"];
            if (showFullDepartments != null && showFullDepartments != string.Empty)
                return showFullDepartments.ToLower() != "false";
            else
                return false;
        }
    }

    protected Guid RootDepartmentID
    {
        get
        {
            if (!string.IsNullOrEmpty(System.Configuration.ConfigurationManager.AppSettings["RootFaceOrganID"]))
                return new Guid(System.Configuration.ConfigurationManager.AppSettings["RootFaceOrganID"]);
            return OrganizationHelper.GetRootDepartmentID();
        }
    }

    protected string[] excludeDeptIDs
    {
        get
        {
            if (!string.IsNullOrEmpty(hdExcludeID.Value))
                return hdExcludeID.Value.ToLower().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            return new string[] { };
        }
    }

    protected string[] selectedDeptIDs
    {
        get
        {
            if (!string.IsNullOrEmpty(hdSelectedID.Value))
                return hdSelectedID.Value.ToLower().Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
            return new string[] { };
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }

    protected void btnConfirm_Click(object sender, EventArgs e)
    {
        StringBuilder sbDeptIDs = new StringBuilder();
        StringBuilder sbDeptNames = new StringBuilder();
        foreach (ListItem li in cblOrgan.Items)
        {
            if (li.Selected)
            {
                sbDeptIDs.Append(";" + li.Value);
                sbDeptNames.Append(";" + li.Text);
            }
        }

        string strDeptID = string.Empty;
        string strDeptName = string.Empty;
        if (sbDeptIDs.Length != 0)
            strDeptID = sbDeptIDs.ToString(1, sbDeptIDs.Length - 1);
        if (sbDeptNames.Length != 0)
            strDeptName = sbDeptNames.ToString(1, sbDeptNames.Length - 1);

        ClientScript.RegisterStartupScript(this.GetType(), "return",
        string.Format("<script>var pDocument = window.dialogArguments;var retValFormat='{0}'; if (retValFormat != null) var retValFormatList = retValFormat.split('|');for (var i = 0; i < retValFormatList.length; i++) {{var retValPair = retValFormatList[i].split(':'); if (retValPair[1] == 'ID') pDocument.getElementById(retValPair[0]).value = '{1}';else if (retValPair[1] == 'DisplayName') pDocument.getElementById(retValPair[0]).value = '{2}';}};window.close();</script>", Request["ReturnValueFormat"], strDeptID, strDeptName));
    }

    private void BindData()
    {
        Guid[] rootDeptIDs = GetRootDepartmentIDs();
        if (rootDeptIDs.Length != 0)
        {
            DataTable dtDepartment = OrganizationHelper.GetDepartmentInfoTableByDepartment(rootDeptIDs[0], false);
            string excludedDepartmentIDs = Wicresoft.Common.Configuration.ConfigurationSettings.AppSettings["WSAF.UserChooser.ExcludedDepartmentIDs"];

            if (ShowFullDepartments)
                excludedDepartmentIDs = string.Empty;

            if (excludedDepartmentIDs != null && excludedDepartmentIDs.Trim().Length > 0)
            {
                string[] ids = excludedDepartmentIDs.Split(',', ';');
                StringBuilder sb = new StringBuilder();
                string spacing = string.Empty;
                foreach (string id in ids)
                {
                    try
                    {
                        Guid departmentID = new Guid(id);
                        sb.AppendFormat("{0}ID = '{1}'", spacing, departmentID.ToString());
                        spacing = " OR ";
                    }
                    catch { }
                }
                string whereClause = sb.ToString();
                if (whereClause.Trim().Length > 0)
                {
                    DataRow[] excludedRows = dtDepartment.Select(whereClause);
                    if (excludedRows.Length > 0)
                    {
                        foreach (DataRow dr in excludedRows)
                        {
                            dtDepartment.Rows.Remove(dr);
                        }
                    }
                }
            }

            this.cblOrgan.DataSource = dtDepartment;
            this.cblOrgan.DataTextField = "DisplayName";
            this.cblOrgan.DataValueField = "ID";
            this.cblOrgan.DataBind();
        }
    }

    private Guid[] GetRootDepartmentIDs()
    {
        return new Guid[] { RootDepartmentID };

        #region 老方案 根据个人权限设置获取RootDepartment
        /*
        ArrayList roots = new ArrayList();

        Guid[] DepartmentIDs = OrganizationHelper.GetUserDepartmentIDListInRole(CurrentUser.ID, Consts.CityAdminRole);
        if (DepartmentIDs.Length == 0)
        {
            DepartmentIDs = OrganizationHelper.GetUserDepartmentIDListInRole(CurrentUser.ID, Consts.RegionAdminRole);
            if (DepartmentIDs.Length == 0)
            {
                DepartmentIDs = OrganizationHelper.GetUserDepartmentIDListInRole(CurrentUser.ID, Consts.CollegeAdminRole);
            }
        }

        foreach (Guid did in DepartmentIDs)
        {
            Guid tmpid = Guid.Empty;
            bool newIsChild = false;
            // 默认，新加，旧不删
            foreach (Guid oldid in roots)
            {
                if (OrganizationHelper.IsDepartmentInDepartment(oldid, did, true))
                {
                    tmpid = oldid;
                    newIsChild = false; // 旧在新内，新加，旧删
                    break;
                }
                else if (OrganizationHelper.IsDepartmentInDepartment(did, oldid, true))
                {
                    newIsChild = true; // 新在旧内，不变化
                    break;
                }
            }
            if (!newIsChild)
                roots.Add(did);
            if (tmpid != Guid.Empty)
                roots.Remove(tmpid);
        }

        return roots.ToArray(typeof(Guid)) as Guid[];
         */
        #endregion
    }

    protected void cblOrgan_PreRender(object sender, EventArgs e)
    {
        CheckBoxList cblOrgan = sender as CheckBoxList;
        foreach (string exId in excludeDeptIDs)
        {
            ListItem li = cblOrgan.Items.FindByValue(exId);
            if (li != null)
                li.Enabled = false;
        }

        foreach (string selId in selectedDeptIDs)
        {
            ListItem li = cblOrgan.Items.FindByValue(selId);
            if (li != null)
                li.Selected = true;
        }
    }
}
